<?php
session_start();
$op = $_GET['op'];
$page    = !empty($_GET['page']) ? intval($_GET['page']) : 1;
$newsid  = intval($_GET['newsid']);

require_once 'inc/config.php';
require_once 'inc/classes/db.php';
require_once 'inc/classes/util.php';
require_once 'include/pagination.php';

$db  = new db( $gDb );
$itemCount  = CountComment($newsid);
$pagination = new Pagination($itemCount);

util::gpc( );
if($op == 'add')
{
	if( empty($_SESSION['user']) )
	{
		echo json_encode(array('rsp'=>false,'msg'=>'login first'));
		exit();
	}	
	InsertComment();
}
$comments = GetComment($newsid,$page);
$ret = array('data'=>$comments,'pagination'=>$pagination->ajaxPagination($page),'total'=>$itemCount);
echo json_encode($ret);
exit( );

function InsertComment()
{
	global $db,$gDb;
	$comment = htmlspecialchars($_GET['comment']);
	$userid  = $_SESSION['user']['id'];
	$newsid  = intval($_GET['newsid']);
	$now     = time();
	$anonymous = $_GET['anonymous']=='true' ? 1 : 0;
	$sql     = "insert into ".$gDb['prefix']."comment (userid,newsid,comment,anonymous,created) values ('$userid','$newsid','$comment','$anonymous','$now')";
	$db->query($sql);
	return true;
}

function GetComment($newsid, $page=1, $pagesize=15)
{
	global $db, $gDb;
	$page = ($page-1)*$pagesize;
	$sql  = "select a.username,b.* from ".$gDb['prefix']."comment b left join ".$gDb['prefix']."users a on a.id=b.userid where newsid=$newsid limit $page, $pagesize";
	$comments = $db->fetchrows($sql);
	$counts = count($comments);
	for($i=0; $i<$counts; $i++) {
		$comments[$i]['comment'] = nl2br($comments[$i]['comment']);
		$comments[$i]['created'] = date('Y-m-d H:i:s', $comments[$i]['created']);
	}
	return $comments;
}

function CountComment($newsid)
{
	global $db,$gDb;
	$sql  = "select count(*) as count from ".$gDb['prefix']."comment where newsid=$newsid";
	$data = $db->fetchrow($sql);
	return $data['count'];
}